package com.itboye.textileexpres.util;

/**
 */

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Random;

/**
 * 下载网页图片到本地
 */
public class DownPicUtil {

	/**
	 * ����ͼƬ������ͼƬ�ĵ�ַ
	 * 
	 * @param url
	 */
	public static void downPic(String url, DownFinishListener downFinishListener) {
		// ��ȡ�洢����Ŀ¼
		String filePath = Environment.getExternalStorageDirectory().getPath();
		File file = new File(filePath + File.separator + "webViewCache");
		if (!file.exists()) {
			file.mkdir();
		}

		loadPic(file.getPath(), url, downFinishListener);

	}

	private static void loadPic(final String filePath, final String url,
			final DownFinishListener downFinishListener) {
		new AsyncTask<Void, Void, String>() {
			String fileName;
			InputStream is;
			OutputStream out;

			@Override
			protected String doInBackground(Void... voids) {
				File picFile = null;
				String[] split = url.split("/");
				String newString = split[split.length - 1];
				if (newString.length() - 20 <= 17) {
					try {
						System.out.println("newString"+newString.length());
					} catch (Exception e) {
						// TODO: handle exception
					}
					return newString.length()+"";
				} else
					try {
						fileName = newString.substring(newString.length() - 20,
								newString.length() - 1);
						picFile = new File(filePath + File.separator + fileName);
					} catch (Exception e) {
						// TODO: handle exception
					}

				if (picFile.exists()) {
					return picFile.getPath();
				}

				try {
					URL picUrl = new URL(url);
					is = picUrl.openStream();
					if (is == null) {
						return null;
					}
					out = new FileOutputStream(picFile);
					byte[] b = new byte[1024];
					int end;
					while ((end = is.read(b)) != -1) {
						out.write(b, 0, end);
					}

					Log.e("OK??", "----------");
					if (is != null) {
						is.close();
					}

					if (out != null) {
						out.close();
					}

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				return picFile.getPath();
			}

			@Override
			protected void onPostExecute(String s) {
				super.onPostExecute(s);
				if (s != null) {
					downFinishListener.getDownPath(s);
				}
			}
		}.execute();
	}

	public interface DownFinishListener {

		void getDownPath(String s);
	}
}
